package com.example.farmrental.controller;

import com.example.farmrental.dto.ApiResponse;
import com.example.farmrental.dto.PageResponse;
import com.example.farmrental.dto.RentalOrderDto;
import com.example.farmrental.entity.RentalOrder;
import com.example.farmrental.service.RentalOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/orders")
@CrossOrigin(origins = "*")
public class RentalOrderController {

    @Autowired
    private RentalOrderService orderService;

    @GetMapping
    public ResponseEntity<ApiResponse<PageResponse<RentalOrderDto>>> list(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String orderDate
    ) {
        PageResponse<RentalOrderDto> data = orderService.list(page, size, status, orderNo, phone, orderDate);
        return ResponseEntity.ok(ApiResponse.success("获取订单列表成功", data));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<RentalOrderDto>> getDetail(@PathVariable Long id) {
        Optional<RentalOrderDto> dto = orderService.getDtoById(id);
        return dto.map(d -> ResponseEntity.ok(ApiResponse.success("获取订单详情成功", d)))
                .orElseGet(() -> ResponseEntity.ok(ApiResponse.error("订单不存在", 404)));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<RentalOrder>> create(@RequestBody Map<String, Object> payload) {
        try {
            RentalOrderDto dto = mapToDto(payload);
            RentalOrder order = orderService.createOrder(dto);
            return ResponseEntity.ok(ApiResponse.success("创建订单成功", order));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("创建订单失败: " + e.getMessage()));
        }
    }

    private RentalOrderDto mapToDto(Map<String, Object> p){
        RentalOrderDto dto = new RentalOrderDto();
        dto.username = asString(p.get("username"));
        dto.phone = asString(p.get("phone"));
        dto.address = asString(p.get("address"));
        dto.status = asString(p.get("status"));
        dto.orderNo = asString(p.get("orderNo"));
        dto.amount = toBigDecimal(p.get("amount"));
        dto.setmealId = toLong(p.get("setmealId"));
        dto.orderTime = parseLdt(asString(p.get("orderTime")));
        dto.startDate = parseLdt(asString(p.get("startDate")));
        dto.endDate = parseLdt(asString(p.get("endDate")));
        Object ml = p.get("machineryList");
        if(ml instanceof Iterable){
            java.util.List<RentalOrderDto.Item> items = new java.util.ArrayList<>();
            for(Object o : (Iterable<?>)ml){
                if(o instanceof Map){
                    Map<?,?> m = (Map<?,?>)o;
                    RentalOrderDto.Item it = new RentalOrderDto.Item();
                    it.machineryId = toLong(m.get("machineryId"));
                    it.name = asString(m.get("name"));
                    it.price = toBigDecimal(m.get("price"));
                    Integer q = toInt(m.get("quantity"));
                    it.quantity = q != null ? q : 1;
                    items.add(it);
                }
            }
            dto.machineryList = items;
        }
        return dto;
    }

    private String asString(Object v){ return v==null? null : String.valueOf(v); }
    private Long toLong(Object v){ try{ return v==null? null : Long.valueOf(String.valueOf(v)); }catch(Exception e){ return null; } }
    private Integer toInt(Object v){ try{ return v==null? null : Integer.valueOf(String.valueOf(v)); }catch(Exception e){ return null; } }
    private java.math.BigDecimal toBigDecimal(Object v){ try{ return v==null? java.math.BigDecimal.ZERO : new java.math.BigDecimal(String.valueOf(v)); }catch(Exception e){ return java.math.BigDecimal.ZERO; } }
    private java.time.LocalDateTime parseLdt(String s){
        if(s==null || s.trim().isEmpty()) return null;
        try{
            if(s.contains("T")) return java.time.LocalDateTime.parse(s);
            java.time.format.DateTimeFormatter f = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            return java.time.LocalDateTime.parse(s, f);
        }catch(Exception e){ return null; }
    }

    @PatchMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Void>> updateStatus(@PathVariable Long id, @RequestBody Map<String, String> payload) {
        try {
            String status = payload.get("status");
            if (status == null || status.trim().isEmpty()) {
                return ResponseEntity.ok(ApiResponse.error("请提供状态参数", 400));
            }
            Optional<RentalOrder> updated = orderService.updateStatus(id, status);
            if (updated.isPresent()) {
                return ResponseEntity.ok(ApiResponse.success("更新状态成功"));
            } else {
                return ResponseEntity.ok(ApiResponse.error("订单不存在", 404));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新状态失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> delete(@PathVariable Long id) {
        try {
            orderService.delete(id);
            return ResponseEntity.ok(ApiResponse.success("删除订单成功"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除订单失败: " + e.getMessage()));
        }
    }
}
